﻿///<reference path="../../jquery-1.3.2-vsdoc.js" />
///<reference path="../Shell/Base.js" />
///<reference path="Dashboard.Manager.js" />

(function($, epi) {
    epi = epi || {};
    epi.dashboard = epi.dashboard || {};
    epi.dashboard.manager = epi.dashboard.manager || {};

    epi.dashboard.manager.gadgetAdd = function() {
        var pub = {};

        var _listCreated = false;
        var _itemList = null;
        var _pagesize = 10;
        var _pages = 1;
        var _isProcessing = false;
        var _sharedResourceKey = "EPiServer.Shell.Resources.Texts";
        var _dashboardResourceKey = "EPiServer.Shell.UI.Views.Dashboard.Resources";

        pub.init = function() {
            /// <summary>
            ///    Init function for epi.dashboard.manager.gadgetAdd functionality
            /// </summary>
            var panel = $('#AddGadgetPanel').append('<ul id="AddGadgetList">')
                    .epiFoldOutPanel({
                        panelClass: "epi-foldOutPanel-wrapped",
                        autoOpen: false,
                        panelHeaderText: epi.shell.resource.get(_dashboardResourceKey, "GadgetAddPanelCaption"),
                        collapseButtonText: epi.shell.resource.get(_sharedResourceKey, "Close"),
                        collapseButtonDescription: epi.shell.resource.get(_dashboardResourceKey, "FoldOutPanelCollapseDescription")
                    })
                    .bind("epifoldoutpanelexpand", epi.shell.layout.reportChanges)
                    .bind("epifoldoutpanelcollapse", epi.shell.layout.reportChanges);
            $('#AddGadgetButton').click(function() {
                if ($('#AddGadgetList').is(':visible')) {
                    panel.epiFoldOutPanel('collapse');
                } else {
                    panel.epiFoldOutPanel('expand');
                    _loadAddGadgetPanel(1, _pagesize);

                    // Since we load the first set of gadgets for the list, we need to update the pager to show the first
                    if (_itemList) {
                        _itemList.epiItemList('changePagerDisplay', 1);
                    }
                }

            });
        };

        var _errorHandler = function(xmlHttpRequest, status, errorThrown) {
            epi.dashboard.manager.feedback.epiFeedback("setErrorMessage", epi.shell.resource.get(_dashboardResourceKey, "ErrorAddGadget"), xmlHttpRequest.responseText);
            _isProcessing = false;

        };

        var _loadAddGadgetPanel = function(currentPage, pageSize) {
            /// <summary>
            ///    Function that loads the content of the Add Gadget foldutpanel.
            /// </summary>
            /// <param name="currentpage" type="Number">
            ///     The current page of which to get the items for
            /// </param>
            /// <param name="pagesize" type="Number">
            ///    The current maxsize of the pages.
            /// </param>
            if (!_isProcessing) {
                _isProcessing = true;

                var data = { pageSize: pageSize, currentPage: currentPage };


                epi.shell.addToAjaxQueue({
                    url: epi.shell.routes.getActionPath({ controller: 'Dashboard', action: 'GetGadgetDefinitions' }),
                    type: "GET",
                    dataType: "json",
                    data: data,
                    error: _errorHandler,
                    success: _getDefinitionsSuccessHandler
                }, { keepFeedback: true });
            }
        };

        var _getDefinitionsSuccessHandler = function(data) {
            /// <summary>
            ///    Function that is called on when a request to the server to get gadget definitions is done successfully.
            /// </summary>
            /// <param name="data" type="Object">
            ///     The data sent from the server containing all definitions.
            /// </param>
            if (!_listCreated) {
                _pages = Math.round((data.count / _pagesize + 0.4));
                _itemList = ($('#AddGadgetList').epiItemList({
                    buttons: {
                        addButton: {
                            text: epi.shell.resource.get(_dashboardResourceKey, "GadgetAddText"),
                            description: epi.shell.resource.get(_dashboardResourceKey, "GadgetAddDescription"),
                            buttonClass: "epi-iconToolbar-add",
                            //When toolbar add is clicked we want to send in the litItem content object connected to this add button.
                            //Also we dont want the div to do logic also so we stop the bubbling of the click.
                            click: function(e) {
                                _addGadget(e, ($(this).closest(".epi-itemList-content")));

                            },
                            clickable: true,
                            tabIndex: -1
                        }
                    },
                    //The 0.4 is added since if we only have 1 item in the last page (like pagesize 3 and we have 4 definitions) 
                    //the last page wont show otherwise due to rounded down.
                    pages: _pages,
                    currentPage: 1,
                    paging: (_pages > 1)
                }).bind("epiitemlistselect", _addGadget)
                            .bind("epiitemlistpagechanged", _pagerPageChanged)
                        );


                _listCreated = true;
            } else if (_pages !== Math.round((data.count / _pagesize + 0.4))) {
                _itemList.epiItemList('setNumberOfPages', _pages);
            }

            $('#AddGadgetList').epiItemList('clear');

            var imageHtml, titleHtml, toolTip, container;

            for (var gadget in data.gadgetDefinitions) {
                imageHtml = $("<img/>")
                            .attr("alt", "")
                            .addClass("epi-itemList-thumb");

                if (data.gadgetDefinitions[gadget].iconUrl !== null) {
                    imageHtml.attr("src", data.gadgetDefinitions[gadget].iconUrl);
                }

                titleHtml = $("<span/>")
                            .addClass("epi-itemList-link")
                            .append(data.gadgetDefinitions[gadget].title);

                toolTip = "";
                if (data.gadgetDefinitions[gadget].tooltip !== null) {
                    toolTip = data.gadgetDefinitions[gadget].tooltip;
                } else if (data.gadgetDefinitions[gadget].description !== null) {
                    toolTip = data.gadgetDefinitions[gadget].description;
                }

                container = $("<div/>")
                            .attr("id", "gadgetdefinition_" + data.gadgetDefinitions[gadget].fullName)
                            .attr("title", toolTip)
                            .addClass("epi-itemList-contentContainer")
                            .append(imageHtml)
                            .append($("<div/>").append(titleHtml));

                _itemList.epiItemList('addItem', container);
            }

            $(".epi-itemList-contentContainer").each(_applyHoverEffect);

            _itemList.epiItemList('setSelectedIndex', 0, true); // To give the first gadgetdefinition tabindex 0.
            _isProcessing = false;

            //Trigger layoutchanged event
            epi.shell.layout.reportChanges();
        };

        var _addGadget = function(e, selectedElement) {
            /// <summary>
            ///    Function that adds the gadget to the dashboard after successful add on the server.
            /// </summary>
            /// <param name="e" type="Event">
            ///     The ajax event that led us here.
            /// </param>
            /// <param name="data" type="Object">
            ///    The object with the data to paste to the dashboard.
            /// </param>
            if (!_isProcessing) {
                _isProcessing = true;
                var content = $(".epi-itemList-contentContainer", selectedElement);
                var controllerType = content.attr("id").replace(/gadgetdefinition_/, "");
                if ($(".epi-gadgetContainer:visible").size() > 0) {
                    var targetContainer = $(".epi-gadgetContainer:visible").eq(0);
                    var targetContainerId = targetContainer.attr("id").replace(/gadgetContainer_/, "");

                    var successHandler = function(data) {
                        targetContainer.prepend(data);
                        epi.shell.runInitFunctions();

                        var options = { to: "#gadgetContainer_" + targetContainerId + " .epi-gadget", className: 'epi-effects-transfer' };

                        var callback = function() {
                            epi.shell.layout.reportChanges();
                            _isProcessing = false;
                        };

                        $(selectedElement).hide("transfer", options, 250, callback);

                    };

                    var data = { containerId: targetContainerId, gadgetTemplateId: controllerType, indexPosition: 0 };

                    epi.shell.addToAjaxQueue({
                        url: epi.shell.routes.getActionPath({ controller: 'Dashboard', action: 'AddGadget' }),
                        type: "POST",
                        dataType: "html",
                        data: data,
                        error: _errorHandler,
                        success: successHandler
                    });
                } else {
                    _isProcessing = false;
                }
            }
        };

        var _pagerPageChanged = function(e, data) {
            /// <summary>
            ///    Function that runs when the page change event is triggered on the pager.
            /// </summary>
            /// <param name="e" type="Event">
            ///     The ajax event that led us here.
            /// </param>
            /// <param name="data" type="Object">
            ///    The object with the data to paste to the dashboard.
            /// </param>
            _loadAddGadgetPanel(data.currentPage, _pagesize);
        };

        var _hoverPanel = null; // used to store the currently showed popup

        // transforms a comma and colon separated list of properties into a html panel
        var _formatTooltip = function(title) {
            if (title) {
                var rows = title.split(/,/g);
                var results = [];
                for (var i in rows) {
                    var pair = rows[i].split(/:/);
                    results.push("<tr><th>" + pair[0] + "</th><td>" + pair[1] + "</td></tr>");
                }
                return "<div class='epi-toolTip'><table>" + results.join("") + "</table></div>";
            }
            return null;
        };

        // shows a tooltip on the row below the currently hovered
        var _applyHoverEffect = function() {
            var tooltipHtml = _formatTooltip(this.title);

            var remove = function() {
                if (_hoverPanel) {
                    _hoverPanel.remove();
                }
                _hoverPanel = null;
            };
            var add = function(e) {
                remove();

                if (tooltipHtml) {
                    var top = $(this).offset().top + $(this).height() + 3;
                    var left = e.pageX;
                    _hoverPanel = $(tooltipHtml).prependTo(document.body);
                    var over = left + _hoverPanel.width() - $(window).width();
                    if (over > 0) {
                        left = left - over - 20;
                    }
                    _hoverPanel.css({ top: top + "px", left: left + "px" }).show();
                }
            };

            $(this).hover(add, remove);

            this.title = "";
        };


        return pub;
    } ();

})(epiJQuery, epi);
